package com.konsung.ksdc.manager.community;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.j256.ormlite.dao.Dao;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.netbean.GroupNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.mqtt.parser.RequestGroupReceivedMessageHandler;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.common.utils.FileUtils;
import com.konsung.ksdc.common.utils.ImageUtils;
import com.konsung.ksdc.common.utils.PhotoUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.TakePicBottomPop;
import com.konsung.ksdc.common.widget.WaitingDialog;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.service.MqttService;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 创建者     kgh
 * 创建时间   2016/6/14 18:29
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class GroupIndexActivity extends Activity {
    private static final String KSKF = "kskf";
    private static final String KSBK = "ksbk";
    private static final String GROUP_ID = "groupId";
    private static final String GROUP_OWNER_ID = "groupOwnerId"; //群主id字段
    private static final String DEFULT_PIC_PATH = "defult";
    @Bind(R.id.edit_group_name)
    EditText editGroupName; // 群聊名称
    @Bind(R.id.txt_group_member_counts)
    TextView txtGroupMemberCounts; // 群成员数量
    @Bind(R.id.img_show_contact)
    ImageView imgShowContact; // 显示好友列表按钮
    @Bind(R.id.gv_group_members)
    GridView gvGroupMembers; // 群成员列表
    //    @Bind(R.id.tv_choice_count)
//    TextView tvChoiceCount; // 选择成员数量
    @Bind(R.id.ll_index_container)
    LinearLayout llIndexContainer; // 群资料容器
    @Bind(R.id.ll_contact_container)
    LinearLayout llContactContainer; // 好友列表容器
    @Bind(R.id.lv_contact)
    ListView lvContact; // 好友列表
    @Bind(R.id.img_contact_back)
    ImageView imgContactBack; // 好友列表返回按钮
    @Bind(R.id.btn_sure)
    TextView btnSure; // 确定选中好友
    @Bind(R.id.btn_save_group)
    Button btnSaveGroup; // 保存群聊
    @Bind(R.id.btn_send_msg)
    Button btnSendMsg; // 保存群聊
    @Bind(R.id.img_back)
    ImageView back;
    @Bind(R.id.iv_new_group_head)
    ImageView ivHead;
    @Bind(R.id.rl_group_head)
    RelativeLayout rlgroupHead;
    @Bind(R.id.tv_selected_count)
    TextView tvSelectedCount;
    private WaitingDialog waitingDialog; //加载界面
    private Uri imageUri;

    private TakePicBottomPop mPopWindom;
    private Map<String, RegisterUserNetBean> userMap = new HashMap<String, RegisterUserNetBean>();
    private List<RegisterUserNetBean> contacts = new ArrayList<RegisterUserNetBean>(); //我的好友数据
    protected List<RegisterUserNetBean> beforeGroupUsers; //增加移除群组成员前的数据，这个可以为null
    private Map<String, String> operationMap = new HashMap<>(); //储存移除或者添加新成员的userId
    private List<String> defultPics = new ArrayList<>();
    private String groupId; //群主题 可为空
    protected String groupOwnerId; //群主id 可为空
    private List<RegisterUserNetBean> groupUsers; //群组
    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    public static final int SELECT_PIC = 3;
    private GroupNetBean group;
    private String picGroupPath;
    private String groupName;
    private GroupContactListAdapter adapter;
    private GroupMemberGridAdapter gridAdapter;
    private boolean isHeadClick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_index);
        ButterKnife.bind(this);
        // 启动activity时不自动弹出软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        this.groupId = getIntent().getStringExtra(GROUP_ID);
        this.groupOwnerId = getIntent().getStringExtra(GROUP_OWNER_ID);
        userMap.put(NetConfig.currentUser.getUserId(), NetConfig.currentUser);

        //群头像默认图片集合
        addGroupHeadPic();
        initComponent();
        initGroupDatas();
    }

    /**
     * 群头像默认图像,保留
     */
    private void addGroupHeadPic() {
        //复制asset的默认图片到sd卡里，方便上传图片到服务器
        FileUtils.copyAssets(this, DEFULT_PIC_PATH, FileUtils.getSdPath(this) + "group_pic");
        defultPics = FileUtils.getAllFiles(FileUtils.getSdPath(this) + "group_pic");
    }

    /**
     * 初始化组件
     */
    private void initComponent() {
        btnSure.setVisibility(View.INVISIBLE);
        //默认生成随机默认图片
        sendPicture(defultPics.get(new Random().nextInt(6)));

        editGroupName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editGroupName.requestFocus();
                editGroupName.setCursorVisible(true);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 显示好友列表按钮
        imgShowContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                llIndexContainer.setVisibility(View.GONE);
                llContactContainer.setVisibility(View.VISIBLE);
            }
        });

        // 后退按钮
        imgContactBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                llContactContainer.setVisibility(View.GONE);
                llIndexContainer.setVisibility(View.VISIBLE);

                initGroupMemberView();
            }
        });

        // 创建群聊
        btnSaveGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String userIds = "";
                for (String userId : userMap.keySet()) {
                    //配合后台规范接口字段
                    userIds += userId + ";";
                }
                groupName = editGroupName.getText().toString();
                if (StringUtils.isEmpty(groupName)) {
                    ToastUtils.toastContent(GroupIndexActivity.this, getString(R.string
                            .tip_group_chat));
                    return;
                }
                if (groupUsers != null) {
                    if (groupUsers.size() < 3) {
                        //当群组成员不足3时，不准创建群
                        ToastUtils.toastContent(GroupIndexActivity.this, getString(R.string
                                .chat_less_two));
                        return;
                    }
                } else {
                    ToastUtils.toastContent(GroupIndexActivity.this, getString(R.string
                            .chat_less_two));
                    return;
                }
                if (picGroupPath == null) {
                    ToastUtils.toastContent(GroupIndexActivity.this, getString(R.string
                            .group_head));
                    return;
                } else {
                    if (picGroupPath.length() == 0) {
                        ToastUtils.toastContent(GroupIndexActivity.this, getString(R.string
                                .group_head));
                        return;
                    }
                }
                showWaitDialog();
                RequestUtils.saveGroup(groupId, groupName, userIds, picGroupPath, NetConfig.
                                currentUser.getUserId(),
                        new RequestCallback() {
                            @Override
                            public void onError(Call call, Exception e) {
                                waitingDialog.dismiss();
                                ToastUtils.toastContent(GroupIndexActivity.this, getString(R.string
                                        .chat_save_faile));
                            }

                            @Override
                            public void onResponse(ResponseBean responseBean) {
                                waitingDialog.dismiss();
                                if (Constants.REQUEST_OK.equals(responseBean.getResultCode())) {

                                    ToastUtils.toastContent(GroupIndexActivity.this, getString(R
                                            .string.chat_save_success));
                                    //创建或者更新群组数据
                                    creatOrUpadate(responseBean);
                                    startToGroup();
                                    editGroupName.setCursorVisible(false);
                                    btnSendMsg.setVisibility(View.GONE);
                                    btnSaveGroup.setVisibility(View.GONE);
                                } else {
                                    ToastUtils.toastContent(GroupIndexActivity.this, getString(R
                                            .string.chat_save_success));
                                }
                            }
                        });
            }
        });

        btnSendMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                addPhoto();
            }
        });
    }

    /**
     * 显示创建群加载loading界面
     */
    private void showWaitDialog() {
        if (waitingDialog == null) {
            waitingDialog = new WaitingDialog(this, "");
            waitingDialog.setText(getString(R.string.tip_loader));
            waitingDialog.show();
        } else {
            waitingDialog.show();
        }
    }

    /**
     * 跳转到群组
     */
    private void startToGroup() {
        Intent intent = new Intent(GroupIndexActivity.this, GroupChatActivity.class);
        intent.putExtra("topicName", groupId);
        intent.putExtra("groupName", editGroupName.getText().toString());
        startActivity(intent);
        finish();
    }

    /**
     * 发送群消息给群里的人
     * @param groupNetBean 群组信息
     */
    private void sendAddGroupMessage(GroupNetBean groupNetBean) {
        //循环发送
        for (RegisterUserNetBean netBean : groupNetBean.getUsers()) {
            String msgSendDate = DateUtils.getStringDateFormat(new Date(),
                    DateUtils.yyyyMMddHHmmss);
            String targetType = MqttMsgUtils.MSG_TARGET_TYPE_GROUP;
            MqttMsgBean bean = new MqttMsgBean();
            bean.setMsgContent(groupNetBean.getGroupId());
            bean.setMsgSendDate(msgSendDate);
            bean.setMsgTargetType(targetType);
            bean.setMsgType(MqttMsgUtils.MSG_TYPE_REQUEST_GROUP);
            bean.setContact(NetConfig.currentUser.getUserId()); //谁发的消息
            bean.setTopicName(netBean.getUserName());

            try {
                byte[] msgContent = new RequestGroupReceivedMessageHandler().parseMessage(bean);
                MqttService.mqttClient.publish(bean.getTopicName(), msgContent, 2, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建群组或者更新群组
     * @param responseBean 后台返回值
     */
    private void creatOrUpadate(ResponseBean responseBean) {
        //后台返回群组id
        groupId = responseBean.getEntity(String.class);

        //没有该群组，继续创建新的数据
        GroupNetBean bean = new GroupNetBean();
        bean.setGroupId(groupId);
        bean.setGroupName(groupName);
        bean.setOwnerId(NetConfig.currentUser.getUserId());
        bean.setGroupOwnerId(NetConfig.currentUser.getUserId());
        bean.setGroupPic(picGroupPath);
        bean.setUsers(groupUsers); //设置群组成员集合
        Dao dao = null;
        try {
            dao = DatabaseHelper.getHelper(GroupIndexActivity.this)
                    .getDao(GroupNetBean.class);
            dao.createOrUpdate(bean);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        sendAddGroupMessage(bean);
    }

    /**
     * 点击添加图片，弹出popwindow。选择图库或拍照的图片。
     */
    private void addPhoto() {
        mPopWindom = new TakePicBottomPop(GroupIndexActivity.this, itemsOnClick);
        mPopWindom.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        mPopWindom.showAtLocation(GroupIndexActivity.this.editGroupName,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPopWindom.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    // 照相
                    clickTakePhoto();
                    break;
                case R.id.btn_album:
                    // 相册
                    clickAlbum();
                    break;
                case R.id.btn_cancel:
                    mPopWindom.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 点击相册（图库）
     */
    private void clickAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_PIC);
    }

    /**
     * 点击拍照
     */
    private void clickTakePhoto() {
        File outputImage = new File(Environment
                .getExternalStorageDirectory(), "test" + System
                .currentTimeMillis() + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO); // 启动相机程序
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    sendPicture(imageUri.getEncodedPath());
                }
                break;

            case CROP_PHOTO:
                try {
                    if (resultCode == RESULT_OK) {
                        sendPicture(imageUri.getEncodedPath());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case SELECT_PIC:
                if (resultCode == RESULT_OK) {
                    sendPicture(PhotoUtils.getPath(this, data.getData()));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 显示图片
     * @param path 图片路径
     */
    private void sendPicture(String path) {
        isHeadClick = true; //只有选择相册上传头像才会出现toast
        PostFormBuilder builder = OkHttpUtils.post();
        ImageUtils imageUtils = new ImageUtils();
        //压缩后的图片
        Bitmap bitmap = imageUtils.ratio(path, 240f, 120f);
        byte[] bytes = imageUtils.getBitmapByte(bitmap);
        File file = new File(path);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        builder.addFile("file", "test+" + System.currentTimeMillis() + "" +
                ".jpg", file);

        String url = NetConfig.getBasicUrl() + "uploadPicture";
        builder.url(url)
                .build()
                .execute(new RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        if (isHeadClick) {
                            //首次进来不弹默认上传头像的提示，只有点击上传头像才会提示
                            ToastUtils.toastContent(GroupIndexActivity.this, getString(R.string
                                    .update_head_faile));
                            isHeadClick = false;
                        }
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String picPath = responseBean.getEntity(String.class);
                        String picUrl = StringUtils.appendPicPath(picPath);
                        picGroupPath = picPath;
                        //设置圆形图片
                        Glide.with(MyApplication.getContext()).load(picUrl).error(R.drawable
                                .pic_head_defult).into(ivHead);
                    }
                });
    }

    /**
     * 初始化群聊界面数据
     */
    private void initGroupDatas() {
        if (StringUtils.isEmpty(groupId)) {
            //没有群创建群
            btnSendMsg.setVisibility(View.GONE);
            initContactDatas();
            return;
        }

        RequestUtils.findCommunityById(groupId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                Toast.makeText(GroupIndexActivity.this, "群聊信息加载失败!",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                group = responseBean.getEntity(GroupNetBean.class);

                userMap.clear();
                for (RegisterUserNetBean user : group.getUsers()) {
                    userMap.put(user.getUserId(), user);
                }

                editGroupName.setText(group.getGroupName());
                txtGroupMemberCounts.setText(group.getUsers().size() + "人");

                // 初始化群成员表格
                initGroupMemberView();

                // 初始化好友列表
                initContactDatas();
            }
        });
    }

    /**
     * 初始化群成员列表
     */
    private void initGroupMemberView() {
        groupUsers = new ArrayList<RegisterUserNetBean>(userMap.values());
        txtGroupMemberCounts.setText(groupUsers.size() + "人");
        gridAdapter = new GroupMemberGridAdapter(groupUsers);
        gvGroupMembers.setAdapter(gridAdapter);
        gvGroupMembers.setOnItemClickListener(new AdapterView
                .OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                    int i, long l) {
                Intent intent = new Intent(GroupIndexActivity.this,
                        ContactIndexActivity.class);

                Gson gson = new Gson();
                intent.putExtra("data", gson.toJson(groupUsers.get(i)));
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化好友列表
     */
    private void initContactDatas() {
        //根据自己的id来查询好友数据
        findMyContacts();
        // 加载好友界面
        loadContactListView();
    }

    /**
     * 加载好友列表界面
     */
    private void loadContactListView() {
        tvSelectedCount.setText(R.string.chat_select_member);
        adapter = new GroupContactListAdapter(1, userMap, contacts, groupOwnerId,
                beforeGroupUsers, operationMap);
        lvContact.setAdapter(adapter);
        if (null != adapter) {
            adapter.setOnCbxStateChangedListener(new GroupContactListAdapter
                    .OnCbxStateChangedListener() {

                @Override
                public void onChange(int selectList) {
                    tvSelectedCount.setText(StringUtils.appendSelected(selectList));
                }
            });
        }
    }

    /**
     * 查询我的好友，除了康尚百科和康尚客服
     */
    private void findMyContacts() {
        //每次进来联系清除，重新数据库获取
        contacts.clear();
        List<RegisterUserNetBean> friends = DatabaseHelper.getHelper(this).getRuntimeExceptionDao(
                RegisterUserNetBean.class).queryForEq("ownerId",
                NetConfig.currentUser.getUserId());

        for (RegisterUserNetBean bean : friends) {
            String userName = bean.getUserName();
            if (userName.equals(KSKF) || userName.endsWith(KSBK)) {
                continue;
            }
            contacts.add(bean);
        }
    }
}
